package com.useeinfo.oa.modules.base.biz;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.useeinfo.framework.extend.biz.CrudBiz;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.func.file.FileUtils;
import com.useeinfo.framework.sugar.tools.Configuration;
import com.useeinfo.framework.sugar.tools.DateTimeUtils;
import com.useeinfo.oa.common.config.ConstantKeyFilePath;
import com.useeinfo.oa.common.enums.ResultEnums;
import com.useeinfo.oa.common.utils.ResultUtil.ResultDto;
import com.useeinfo.oa.common.utils.ResultUtil.ResultUtil;
import com.useeinfo.oa.modules.base.dao.FacilityDao;
import com.useeinfo.oa.modules.base.entity.Enterprise;
import com.useeinfo.oa.modules.base.entity.Facility;
import com.useeinfo.oa.modules.base.entity.FacilityCat;
import com.useeinfo.oa.modules.base.entity.Resource;
import com.useeinfo.oa.modules.base.enums.ResourceTypeEnum;
import com.useeinfo.oa.modules.security.entity.SystemUser;
import com.useeinfo.oa.modules.security.util.SessionKeyUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Auther: bin.liu
 * @Date: 2018/12/4 18:50
 * @Description: 设备管理service
 */
@Service
public class FacilityBiz extends CrudBiz<FacilityDao, Facility> {
    @Autowired
    private FacilityCatBiz facilityCatBiz;
    @Autowired
    private ResourceBiz resourceBiz;
    @Autowired
    private HttpServletRequest httpServletRequest;

    public Boolean existFacility(Facility facility, Long enterpriseId) {
        if (StringUtils.isBlank(facility.getCode())) {
            return true;
        }
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("enterpriseId", enterpriseId+"");
        queryParam.getSqlMap().put("codeOrQRCode", facility.getCode());
        List<Facility> facilityList1 = findList(queryParam);
        queryParam.getSqlMap().put("codeOrQRCode", facility.getQrCode());
        List<Facility> facilityList2 = findList(queryParam);
        if (facility.getId() == null) {
            return CollectionUtils.isNotEmpty(facilityList1)||CollectionUtils.isNotEmpty(facilityList2);
        } else {
            return (!((facilityList1.size() == 1 && facilityList1.get(0).getId().equals(facility.getId())) || facilityList1.size() == 0))
                    ||
                    (!((facilityList2.size() == 1 && facilityList2.get(0).getId().equals(facility.getId())) || facilityList2.size() == 0));
        }



    }

    public List<Facility> findModeIn(List<String> ids){
        if (CollectionUtils.isEmpty(ids)) {
            return new ArrayList<>();
        }
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("ids", ids + "");

        List<Facility> facilityList = dao.findList(queryParam);
        return facilityList;
    }

    /**
     * 获取设备流水号
     *
     * @param enterpriseId
     * @return
     */
    public String getSerialCode(String enterpriseId) {
        String serialCode = enterpriseId + "-" + DateTimeUtils.formatDateToStringWithOnlyDate(new Date(), "yyyyMMdd") + "-" + (int) ((Math.random() * 9 + 1) * 100000);
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("serialCode", serialCode);
        List<Facility> facilityList = this.findList(queryParam);
        if (CollectionUtils.isNotEmpty(facilityList)) {
            return getSerialCode(enterpriseId);
        } else {
            return serialCode;
        }
    }



    /**
     * 判断是否有该设备(有返回 没有返回NULL)
     *
     * @param enterpriseId
     * @return
     */
    public Facility getFacilityByCode(String facilityCode,String enterpriseId) {
        if(StringUtils.isBlank(facilityCode)||StringUtils.isBlank(enterpriseId)){
            return null;
        }
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("enterpriseId", enterpriseId+"");
        queryParam.getSqlMap().put("code", facilityCode);
        List<Facility> facilityList = this.findList(queryParam);
        if(CollectionUtils.isNotEmpty(facilityList)){
            return facilityList.get(0);
        }
        return null;
    }

    /**
     * 按专业分类查询设备数量
     *
     * @param enterpriseIds
     * @return
     */
    public JSONArray groupByRootCat(String enterpriseIds) {
        JSONArray rows = new JSONArray();
        if(StringUtils.isBlank(enterpriseIds)){
            return rows;
        }
        List<Object[]> objects = dao.getFacilityCountListGroupByCat(enterpriseIds);
        for(Object obj[] : objects){
            JSONObject json = new JSONObject();
            Long rootCatId = obj[0]==null?null:((BigInteger) obj[0]).longValue();
            Integer count = ((BigInteger) obj[1]).intValue();
            if(rootCatId!=null){
                FacilityCat rootCat = facilityCatBiz.findModel(rootCatId);
                json.put("rootCatName",rootCat.getCatName());
            }else{
                json.put("rootCatName","未分配");
            }
            json.put("rootCatId",rootCatId);
            json.put("count",count);
            rows.add(json);
        }
        return rows;
    }

    /**
     * 根据所给的企业ids查询总设备数
     * @param enterpriseIds
     * @return
     */
    public int facilityCount(String enterpriseIds,String beforeCreateDate) {
        if(StringUtils.isBlank(enterpriseIds)){
            return 0;
        }
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("enterpriseIds",enterpriseIds);
        if(StringUtils.isNotBlank(beforeCreateDate)){
            queryParam.getSqlMap().put("beforeCreateDate",beforeCreateDate);
        }
        Long facilityCount = this.totalRecord(queryParam.getSqlMap());
        if(facilityCount!=null){
            return facilityCount.intValue();
        }else{
            return 0;
        }
    }


    public ResultDto upload(MultipartFile file, String type) {
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        if (file == null || StringUtils.isBlank(type)) {
            return ResultUtil.error("参数错误");
        }
        Resource resource = new Resource();
        String savePath = "";
        if ("img".equals(type)) {
            savePath = FileUtils.fileUpload(file, ConstantKeyFilePath.FACILITY_IMG_DIR, ConstantKeyFilePath.FACILITY_IMG_FIX, Configuration.getConfigurationByName("fileSaveRootPath"));
            resource.setResourceName("设备图片");
            resource.setResourceTypeEnum(ResourceTypeEnum.IMG);
        }
        resource.setPath(savePath);
        resource.setEnterprise(sessionEnterprise);
        resource.setCreateDate(new Date());
        resourceBiz.addOrUpdate(resource);
        return ResultUtil.success(resource.toJSONObject());
    }
}
